Ext.ns('Tm.category');
Tm.category.CategoryIndexPanel = Ext.extend(Ext.Panel, {
			id:'categoryIndexPanel',
			frame : true,
			autoWidth : true,
			layout : 'fit',
			initComponent : function() {	
				var gridId = Ext.id();
				var form = new Tm.common.FormPanel({
							layout : 'table',
							layoutConfig : {
								columns : 3
							},
							defaults : {
								xtype : 'textfield',
								margins : '0 5 0 0'
							},
							items : [{
										plugins : [Ext.ux.FieldLabeler],
										name : 'name',
										fieldLabel : '分类名称'
									}, {
										plugins : [Ext.ux.FieldLabeler],
										name : 'code',
										fieldLabel : '分类编码'
									}, {
										plugins : [Ext.ux.FieldLabeler],
										xtype : 'googlesearchfield',
										fieldLabel : '所属父类',
										//allowBlank : false,
										name : 'parent',
										queryURL : 'category/goolgeL1AndL2Category.do',
										colspan : 1
									}]
						});

				var sm = new Ext.grid.CheckboxSelectionModel();

				
				var cm = new Ext.grid.ColumnModel([	sm, {
							header : 'id',
							width : 20,
							dataIndex : 'id',
							hidden : true
						}, {
							header : '编码',
							width : 40,
							dataIndex : 'code',
							//align : 'center',
							sortable : true,
							editor : {
								xtype : 'textfield',
								allowBlank : false
							}
						}, {
							header : '所属父类',
							width : 40,
							dataIndex : 'parent',
							//align : 'center',
							sortable : true,
							xtype : 'combocolumn',
							gridId : gridId,
							editor : new Ext.form.ComboBox({
										id:'parentCategoryComboBox',
										store : new Ext.data.JsonStore({
													url : 'category/getL1AndL2Category.do',
													autoLoad : true,
													fields : [{
																name : 'id'
															}, {
																name : 'code'
															}],
															listeners : {
																load : function() {
																	var categoryIndexPanel=Ext.getCmp('categoryIndexPanel');
																	var gridStore=categoryIndexPanel.grid.store;
																	gridStore.fireEvent('gridLoad4parentUpdated',gridStore);
																	///girdStore.load();
																	
																}
															}	
												}),
										displayField : 'code',
										valueField : 'id',
										hiddenName : 'id',
										allowBlank : true,
										minChars : 1,
										hideTrigger: true,
										typeAhead : true,
										mode : 'remote',
										triggerAction : 'all',
										emptyText : '',
										selectOnFocus : true,
										forceSelection : true
									})
						}, {
							header : '中文名称',
							width : 80,
							dataIndex : 'cnName',
							sortable : true,
							editor : {
								xtype : 'textfield',
								allowBlank : false
							},
							renderer:   function (data, metadata, record, rowIndex, columnIndex, store) {  
							    metadata.attr = 'ext:qtitle="' + this.header+ '"' + ' ext:qtip="' + data + '"';  
							    return data;  
							}
						}, {
							header : '英文名称',
							width : 80,
							dataIndex : 'enName',
							sortable : true,
							editor : {
								xtype : 'textfield',
								allowBlank : true
							},
							renderer:   function (data, metadata, record, rowIndex, columnIndex, store) {  
							    metadata.attr = 'ext:qtitle="' + this.header+ '"' + ' ext:qtip="' + data + '"';  
							    return data;  
							}
						}, {
							header : '描述',
							width : 100,
							dataIndex : 'description',
							//align : 'center',
							sortable : true,
							editor : {
								xtype : 'textfield',
								allowBlank : true
							},
							renderer:   function (data, metadata, record, rowIndex, columnIndex, store) {  
							    metadata.attr = 'ext:qtitle="' + this.header+ '"' + ' ext:qtip="' + data + '"';  
							    return data;  
							}
						}]);
				
				cm.defaultSortable = true;
				var fields = [{
							name : 'id',
							type : 'int',
							mapping : 'id'
						}, {
							name : 'code',
							type : 'string',
							mapping : 'code'
						}, {
							name : 'parent',
							type : 'string',
							mapping : 'parent'
						}, {
							name : 'cnName',
							type : 'string',
							mapping : 'cnName'
						}, {
							name : 'enName',
							type : 'string',
							mapping : 'enName'
						}, {
							name : 'description',
							type : 'string',
							mapping : 'description'
						}, {
							name : 'hasChildren',
							type : 'string',
							mapping : 'hasChildren'

						}];
				var ds = new Ext.data.Store({
							proxy : new Ext.data.HttpProxy({
										url : 'category/queryCategory.do'
									}),
							reader : new Ext.data.JsonReader({
										totalProperty : 'totalProperty',
										root : 'root',
										id : 'id',
										fields : fields
									}),
							baseParams : {
								start : 0,
								limit : 20
							},

							sortInfo : {
								field : 'id',
								direction : 'ASC'
							},
							autoLoad : true,
							listeners : {
								beforeload : function() {
									Ext.apply(this.baseParams, form.getForm().getFieldValues(false));
								} 
							}
							
						}

				);
				ds.addEvents('gridLoad4parentUpdated');

//				var editor = new Ext.ux.grid.RowEditor({
//							// clicksToEdit : 2,
//							// this changes from the default double-click activation to single click activation
//							errorSummary : false,// disables display of validation messages if the row is invalid
//							listeners : {
//
//								afteredit : function(roweditor, changes, record, rowIndex) {
//									//console.dir(record);
//									Ext.Ajax.request({
//												url : 'category/saveOrUpdateCategory.do',
//												method : 'POST',
//												params : record.data,
//												success : function() {
//													record.store.load();
//												}
//											});
//								},
//								canceledit : function(roweditor, pressed) {
//								//	console.dir(roweditor);
//
//									if (!roweditor.record.data.id) {
//										roweditor.grid.getStore().remove(roweditor.record);
//									}
//
//								},
//
//								move : function(p) {
//									this.resize();
//								},
//								hide : function(p) {
//									var mainBody = this.grid.getView().mainBody;
//									var lastRow = Ext.fly(this.grid.getView().getRow(this.grid.getStore().getCount() - 1));
//									mainBody.setHeight(lastRow.getBottom() - mainBody.getTop(), {
//												callback : function() {
//													mainBody.setHeight('auto');
//												}
//											});
//								},
//								afterlayout : function(container, layout) {
//									this.resize();
//								}
//							},
//							resize : function() {
//								var row = Ext.fly(this.grid.getView().getRow(this.rowIndex)).getBottom();
//								var lastRow = Ext.fly(this.grid.getView().getRow(this.grid.getStore().getCount() - 1)).getBottom();
//								var mainBody = this.grid.getView().mainBody;
//								var h = Ext.max([row + this.btns.getHeight() + 10, lastRow]) - mainBody.getTop();
//								mainBody.setHeight(h, true);
//							}
//						});
				var grid = new Ext.grid.GridPanel({
							ref:'grid',
							id : gridId,
							store : ds,
							sm : sm,
							cm : cm,
							//region : 'center',
							border : false,
							stripeRows : true,
							autoHeight : true,
							autoExpandColumn : 'description',
							viewConfig : {
								forceFit : true
							},
						//	plugins : [editor],
							bbar : new Ext.PagingToolbar({
										plugins : new Ext.ux.ProgressBarPager(),
										pageSize : 20,
										store : ds,
										displayInfo : true,
										emptyMsg : '没有记录'
									}),

							listeners : {
				 celldblclick : function(grid, rowIndex, columnIndex, event) {
							 var store = grid.getStore();
							 var data = store.getAt(rowIndex).data;
							
							 var categoryAddPanel = new Tm.category.CategoryAddPanel({
							 dataId : data.id
							 });
							 var categoryAddWindow = new Tm.common.CommonWindow({
							 id : 'categoryAddWindow',
							 title : '更新分类',
							 items : categoryAddPanel
							 });
							 categoryAddWindow.on('close', function(panel) {
								 var categoryIndexPanel =Ext.getCmp('categoryIndexPanel');
								 var parentCategoryComboBox=Ext.getCmp('parentCategoryComboBox');
								 categoryIndexPanel.fireEvent('parentUpdated', parentCategoryComboBox.store,ds);
							 });
							 categoryAddWindow.show();
							
							 }
							}
						});
				var toolBar = new Ext.Toolbar({
							hideBorders : true,
							buttons : [{
										text : '查询',
										iconCls : 'act_queryIcon',
										handler : function() {
											ds.load();
										}
									}, {
										xtype : 'tbseparator'
									}, {
										text : '重置',
										iconCls : 'act_resetIcon',
										handler : function() {
											form.getForm().reset();
										}
									}, {
										xtype : 'tbseparator'
									}, {
										text : '新增',
										iconCls : 'act_addIcon',

										handler : function() {
											 var categoryAddPanel = new Tm.category.CategoryAddPanel({
												 });
												 var categoryAddWindow = new Tm.common.CommonWindow({
												 id : 'categoryAddWindow',
												 title : '新增分类',
												 items : categoryAddPanel
												 });
												 categoryAddWindow.on('close', function(panel) {
													 var categoryIndexPanel =Ext.getCmp('categoryIndexPanel');
													 var parentCategoryComboBox=Ext.getCmp('parentCategoryComboBox');
													 categoryIndexPanel.fireEvent('parentUpdated', parentCategoryComboBox.store,ds);
													 
												 
												 });
												 categoryAddWindow.show();
										}
									}, {
										xtype : 'tbseparator'
									}, {
										text : '删除',
										iconCls : 'act_deleteIcon',

										handler : function() {
											//editor.stopEditing();
											
											var records = grid.getSelectionModel().selections.items;
											var ids=[];
											if (records.length == 0) {
												return;
											} else  {
												var breakException='break';
												try {
													records.forEach(function(record, index, array){
	 													if(record.data.hasChildren=='true'){
	 														App.setAlert('notice', '所选分类包含其他子类，请手动删除其子类或者将其子类移至其他分类下再进行删除。');
															throw breakException;
 														}else{
															ids.push(record.data.id);
														}
													});
														
												} catch(e) {
												    if (e!==breakException) {
												    	throw e;
												    }else{
												    	return;
												    }
												}

															
											} 
												Ext.MessageBox.confirm('注意', '您确定要进行该操作？', function(btn) {
															if (btn == 'yes') {

																Ext.Ajax.request({
																			url : 'category/deleteCategories.do',
																			method : 'POST',
																			params : {
																				ids : ids
																			},
																			success : function(action, response) {
																				grid.getStore().load();
																			},
																			failure : function(action, response) {
																				App.setAlert('notice', '此分类存在关联案件，排除关联操作。');
																			}
																		});
															}

														});
 
										}
									}]
						});
				Ext.apply(this, {
							tbar : toolBar,
							items : [form, grid]
						});
				Tm.category.CategoryIndexPanel.superclass.initComponent.call(this);
				this.addEvents('parentUpdated');
			},
			listeners : {
					parentUpdated : function(parentStore,gridStore) {
						gridStore.on('gridLoad4parentUpdated',this.parentUpdatedHandler);
						parentStore.load();
					}
				},
			parentUpdatedHandler : function(parentStore,gridStore){
				 var categoryIndexPanel =Ext.getCmp('categoryIndexPanel');
				 var gridStore=categoryIndexPanel.grid.store
				 gridStore.load();
				 gridStore.un('gridLoad4parentUpdated',this.parentUpdatedHandler);
				//gridStore.load();
				//console.log(gridStore.hasListener('gridLoad4parentUpdated'));
			}
		});
